<?php

namespace app\api\controller;

use app\common\util\LogHelper;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Kernel\Messages\Transfer;
use think\facade\Log;

class WechatCustomerService extends Base
{

    public function index()
    {

        //http://xiaoxin.itbbn.top/demo_list/xcx_kefu/api/public/index.php/api/WechatCustomerService/index/
        $config = $this->getConfig();
//        Factory::miniProgram();
        $app = Factory::miniProgram($config);
        /**
         * [2022-10-15T16:02:05+08:00][info] GET  {"signature":"b49a42b9f92f3d9c40132d8ff403b0e7b28865a7","echostr":"6093338965983620095","timestamp":"1665820924","nonce":"2056756464"}
         * [2022-10-15T16:02:05+08:00][info] input  {"signature":"b49a42b9f92f3d9c40132d8ff403b0e7b28865a7","echostr":"6093338965983620095","timestamp":"1665820924","nonce":"2056756464"}
         */


        LogHelper::log("消息处理开始");
        $app->server->push(function ($message) use ($app) {
            LogHelper::log("消息：" . json_encode($message, JSON_UNESCAPED_UNICODE));
            LogHelper::log("当前消息类型：" . $message["MsgType"]);
            if (1 == 1) {
                //发送客服消息
                if ($message['MsgType'] == "event" && $message["Event"] == "user_enter_tempsession") {
                    //如果是客服消息
                    /**
                     * <xml>
                     * <ToUserName><![CDATA[gh_df3bde050fac]]></ToUserName>
                     * <FromUserName><![CDATA[orIIY45qRoczRpbydg6JK2HlZ7zA]]></FromUserName>
                     * <CreateTime>1665858236</CreateTime>
                     * <MsgType><![CDATA[event]]></MsgType>
                     * <Event><![CDATA[user_enter_tempsession]]></Event>
                     * <SessionFrom><![CDATA[刘先生]]></SessionFrom>
                     * </xml>
                     */
                    $app->customer_service->message("1.0您好：" . $message["SessionFrom"])->to($message["FromUserName"])->send();
//                        return new Text("欢迎您：".$message["SessionFrom"]);
                } else {
                    $app->customer_service->message("1.0请稍等刘先生")->to($message["FromUserName"])->send();
                }
//                return;
                return new Transfer();
            }
            /*switch ($message['MsgType']) {
                case 'event':
                    //{"ToUserName":"gh_df3bde050fac","FromUserName":"orIIY45qRoczRpbydg6JK2HlZ7zA","CreateTime":1665857137,"MsgType":"event","Event":"user_enter_tempsession","SessionFrom":"刘先生"}
                    if ($message["Event"] == "user_enter_tempsession") {
                        //如果是客服消息
                        return new Transfer();
//                        return new Text("欢迎您：".$message["SessionFrom"]);
                    }
                    return '收到事件消息';
                    break;
                case 'text':
                    return '收到文字消息：' . $message["Content"] . " |" . getNow();
                    break;
                case 'image':
                    return '收到图片消息';
                    break;
                case 'voice':
                    return '收到语音消息';
                    break;
                case 'video':
                    return '收到视频消息';
                    break;
                case 'location':
                    return '收到坐标消息';
                    break;
                case 'link':
                    return '收到链接消息';
                    break;
                case 'file':
                    return '收到文件消息';
                // ... 其它消息
                default:
                    return '收到其它消息';
                    break;
            }*/

            // ...
        });
        $response = $app->server->serve();
        LogHelper::log("消息处理结束");
//        print_r($response->getContent());

//        return $response;

//        return "success";
        return $response->send();
        //$response->send();
        /*LogHelper::log("消息内容：" . json_encode($app->server->getMessage(), JSON_UNESCAPED_UNICODE));
        //print_r($app->server->getMessage());
        $returnStr = $response->getContent();
        $echostr = input("echostr", "");

        if ($echostr) {
            //如果是验证
            LogHelper::log("这是绑定消息接口");
            return $echostr;
        }
        return $returnStr;*/
        //$echostr = input("echostr", "");
        //return $echostr;
        //Log::write(print_r($response, true), "debug");
//        return $response;
// 将响应输出
//        $response->send();exit; // Laravel 里请使用：return $response;
    }


    public function testGetMsgList()
    {
        $config = $this->getConfig();
//        Factory::miniProgram();
        $app = Factory::miniProgram($config);
        $list = $app->customer_service->list();
        print_r($list);
        $chatList = $app->customer_service->messages(time() - 3600, time(), $msgId = 1, $number = 10000);
        print_r($chatList);
    }

    /**
     * @return string[]
     */
    public function getConfig(): array
    {
        $config = [
            'app_id' => 'wx01bcf7201af4916b',
            'secret' => '64174dbf24b4e880ee708e8b53eef81f',
            'token' => 'TestToken',
            'response_type' => 'array',
            'aes_key' => '6mUcGKx9Jlh6ZfOouLpitsq19bTAVARGS6tydq17Ox4',// EncodingAESKey，兼容与安全模式下请一定要填写！！！
            //...
        ];
        return $config;
    }
}